package practise.mulitThreads.ConcurrentInPractice.CustomerizedCounter;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by richard on 6/14/14.
 */
public class SimulatedCAS {
    int count = 0;
    Lock lock = new ReentrantLock();
    public int compareAndSwap(int expected,int update){

        try{
            lock.lock();
            int oldValue = count;
            if(expected==oldValue){
                count=update;
            }
            return oldValue;
        }
        finally {
            lock.unlock();
        }


    }
    public boolean compareAndSet(int expected,int update){
        lock.lock();
        try{
            return expected==compareAndSwap(expected,update);
        }
        finally {
            lock.unlock();
        }
    }

    public Integer get(){
        return count;
    }
}
